package com.shiyi.utils;

import com.shiyi.dto.email.EmailParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;


/**
 * @author mdy
 * * @date 2024/9/2
 */
public class EmailUtil {

    private final static Logger logger = LoggerFactory.getLogger(EmailUtil.class);
    /**
     * @param from    邮件发送者
     * @param subject 主题
     * @param content 内容
     * @param to      邮件接收者，可变形参，可传入多个，当作数组使用，编译时也会转为数组
     */
    public static void sendSimpleEmail(JavaMailSender sender, String from, String subject, String content, String... to) {

        if (verify(subject, content, to)) {
            MimeMessage mimeMessage = sender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = null;
            try {
                mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
                mimeMessageHelper.setFrom(from);
                mimeMessageHelper.setTo(to);
                mimeMessageHelper.setSubject(subject);
                mimeMessageHelper.setText(content);
                sender.send(mimeMessage);
            } catch (MessagingException e) {
                logger.error("邮件发送失败", e);
            }
        }
    }

    /**
     * 发送HTML邮件
     *
     * @param from    邮件发送者
     * @param subject 主题
     * @param content 邮件内容
     * @param to 邮件接收者
     */
    public static void sendHtmlMail(JavaMailSender sender, String from, String subject, String content, String[] to) {
        if (verify(subject, content, to)) {
            //获取MimeMessage对象
            MimeMessage mimeMessage = sender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = null;
            try {
                mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
                mimeMessageHelper.setFrom(from);
                mimeMessageHelper.setTo(to);
                mimeMessageHelper.setSubject(subject);
                mimeMessageHelper.setText(content, true);
                //发送
                sender.send(mimeMessage);
            } catch (MessagingException e) {
                logger.error("邮件发送失败", e);
            }
        }
    }

    /**
     * 发送带附件的邮件
     *
     * @param from     邮件发送者
     * @param subject  邮件主题
     * @param content  邮件内容
     * @param filePath 附件路径
     * @param to       邮件接收者
     */
    public static void sendAttachmentsMail(JavaMailSender sender, String from, String subject, String content, String filePath, String... to) {
        if (verify(subject, content, to)) {
            MimeMessage mimeMessage = sender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = null;
            try {
                mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
                mimeMessageHelper.setFrom(from);
                mimeMessageHelper.setTo(to);
                mimeMessageHelper.setSubject(subject);
                mimeMessageHelper.setText(content);
                FileSystemResource file = new FileSystemResource(new File(filePath));
                String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
                mimeMessageHelper.addAttachment(fileName, file);
                sender.send(mimeMessage);
            } catch (MessagingException e) {
                logger.error("邮件发送失败", e);
            }

        }

    }

    /**
     * html模板邮件
     *
     * @param from       发件人
     * @param to         收件人
     * @param subject    邮件主题
     * @param emailParam 给模板的参数
     * @param template   html模板路径(相对路径)  Thymeleaf的默认配置期望所有HTML文件都放在 **resources/templates ** 目录下，以.html扩展名结尾。
     * @throws MessagingException
     */
    public static void thymeleafEmail(JavaMailSender sender, TemplateEngine engine, String from, String subject, EmailParam emailParam, String template, String... to) {
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            // 利用 Thymeleaf 模板构建 html 文本
            Context ctx = new Context();
            // 给模板的参数的上下文
            ctx.setVariable("emailParam", emailParam);
            // 执行模板引擎，执行模板引擎需要传入模板名、上下文对象
            // Thymeleaf的默认配置期望所有HTML文件都放在 **resources/templates ** 目录下，以.html扩展名结尾。
            // String emailText = templateEngine.process("email/templates", ctx);
            String emailText = engine.process(template, ctx);
            mimeMessageHelper.setText(emailText, true);

//                FileSystemResource logoImage= new FileSystemResource("D:\\image\\logo.jpg");
            //绝对路径
//            FileSystemResource logoImage = new FileSystemResource(imgPath);
            //相对路径，项目的resources路径下
//            ClassPathResource logoImage = new ClassPathResource("static/image/logonew.png");
            //一般文件附件调用这个方法
            try {
                URL url = new URL(emailParam.getAttachment());
                DataSource dataSource = new URLDataSource(url);
                String fileName = emailParam.getShopName() + "消费券记录电子发票.pdf";
                mimeMessageHelper.addAttachment(fileName, dataSource);
            } catch (MalformedURLException e) {
                logger.error("邮件发送失败", e);
            }

            sender.send(mimeMessage);
        } catch (MessagingException e) {
            logger.error("发票邮件发送失败！");
        }
    }

    /**
     * 邮件必要信息校验
     *
     * @param subject 主题
     * @param content 邮件内容
     * @param to      邮件收件人
     */
    public static boolean verify(String subject, String content, String[] to) {
        return to != null && to.length != 0 &&
                !isAllBlank(subject, content);
    }
    public static boolean isAllBlank(String... strings) {
        for (String string : strings) {
            if (!StringUtils.isBlank(string)) {
                return false;
            }
        }
        return true;
    }
}
